from django.views.generic import View

from utils import restful, md5, tokens
from .serializers import UsersSerializer
from ..aiauth.models import *


class login_view(View):
    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        try:
            user = Users.objects.get(studentid=username, password=md5.md5(password))
            token_data = {
                'user_id': user.user_id,
                'role_id': user.role_id
            }
            token = tokens.Token.create_token(data=token_data)
            # 设置token过期时间，单位秒
            # cache.set(user.user_id, token, 60 * 1)
            return restful.ok(
                message="登陆成功！",
                data={
                    'user_id': user.user_id,
                    'token': token
                }
            )
        except:
            return restful.params_error(message="账号或密码错误，请重新输入！")


def getUserInfo(request):
    user_id = request.GET.get('user_id')
    userinfo = Users.objects.get(user_id=user_id)
    data = UsersSerializer(userinfo).data
    return restful.ok(data=data)
